package com.btshop.file.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

/**
 * @ClassName: FileUtil
 * @description: 文件处理工具类
 * @author: 李东
 * @Date: 2020-7-16 14:24
 */
@Slf4j
public class FileUtil {

    /**
     * @description: MultipartFile 转换 File,生成临时文件，调用链完成时需要删除临时文件
     * @Param: [file]
     * @return: java.io.File
     * @author: 李东
     * @time: 2020-7-16 16:02
     **/
    public static File MultipartFileToFile(MultipartFile file) {
        try {
            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);

                    return newFile;
                }
            }
            throw new RuntimeException("文件无内容！");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("MultipartFile 转换 File 异常！");
        }
    }


    /**
     * @description: 删除文件，可以是文件或文件夹
     * @Param: [fileName]
     * @return: boolean
     * @author: 李东
     * @time: 2020-7-16 14:48
     **/
    public static boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            log.info("删除文件失败:" + fileName + "不存在！");
            return false;
        } else {
            if (file.isFile()) {
                return deleteFile(fileName);
            } else {
                return deleteDirectory(fileName);
            }
        }
    }

    /**
     * @description: 删除单个文件
     * @Param: [fileName]
     * @return: boolean
     * @author: 李东
     * @time: 2020-7-16 14:48
     **/
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                log.info("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                log.info("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            log.info("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    /**
     * @description: 删除目录及目录下的文件
     * @Param: [dir]
     * @return: boolean
     * @author: 李东
     * @time: 2020-7-16 14:48
     **/
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator)) {
            dir = dir + File.separator;
        }
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            log.info("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = FileUtil.deleteFile(files[i].getAbsolutePath());
                if (!flag) {

                    break;
                }
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = FileUtil.deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {

                    break;
                }
            }
        }
        if (!flag) {
            log.info("删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            log.info("删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }
        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }
        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ((hasRead = fis.read(bbuf)) > 0) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件读取byte[] 数组
     */
    public static byte[] readFileByBytes(InputStream file) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(file);
            short bufSize = 1024;
            byte[] buffer = new byte[bufSize];
            int len1;
            while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                bos.write(buffer, 0, len1);
            }
            byte[] var7 = bos.toByteArray();
            return var7;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException var14) {
                var14.printStackTrace();
            }
            bos.close();
        }
    }

    /**
     * 根据网址路径获取文件的输入流字节数组
     * 
     * @param strUrl
     * @return
     */
    public static byte[] getFileBytesByUrl(String strUrl) {
        HttpURLConnection httpConn = null;
        try {
            URL url = new URL(strUrl);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(20 * 1000);
            httpConn.connect();
            InputStream inputStream = httpConn.getInputStream();
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            inputStream.close();
            byte[] fileData = output.toByteArray();
            output.close();
            return fileData;
        } catch (Exception e) {
            log.error("getFileBytesByUrl exception :  {}", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
    }


    /**
     * 根据网址路径获取文件的base64字符串
     * 
     * @param strUrl
     * @return
     */
    public static String getFileStringByUrl(String strUrl) {
        HttpURLConnection httpConn = null;
        try {
            URL url = new URL(strUrl);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(20 * 1000);
            httpConn.connect();
            InputStream inputStream = httpConn.getInputStream();
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            inputStream.close();
            byte[] fileDatas = output.toByteArray();
            output.close();
            String encode = new BASE64Encoder().encode(fileDatas);
            return encode;
        } catch (Exception e) {
            log.error("getFileStringByUrl  exception :  {}", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
    }

    /**
     * 根据网址路径获取文件的base64字符串
     * 
     * @param strUrl
     * @return
     */
    public static InputStream getFileInputstreamByUrl(String strUrl) {
        HttpURLConnection httpConn = null;
        try {
            URL url = new URL(strUrl);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(20 * 1000);
            httpConn.connect();
            InputStream inputStream = httpConn.getInputStream();
            return inputStream;
        } catch (Exception e) {
            log.error("getFileInputstreamByUrl  exception :  {}", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
    }

    /**
     * @description: 根据InputStream获取文件的字节数组
     * @Param: [io]
     * @return: byte[]
     * @author: 李东
     * @time: 2020-7-6 18:46
     **/
    public static byte[] getFileBytesByInputStream(InputStream io) {
        try {
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = io.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
            io.close();
            byte[] fileData = output.toByteArray();
            output.close();
            return fileData;
        } catch (Exception e) {
            log.error("Get bytes By InputStream exception :  {}", e);
            throw new RuntimeException("根据InputStream获取文件字节数组异常", e);
        }
    }


}
